<template>
  <a-modal v-model:visible="visible" :title="modalTitle" width="35%" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="formState" ref="formRef" :label-col="{ span: 5 }">
      <a-form-item label="标题" name="title" :rules="[{ required: true, message: '请输入标题' }]">
        <a-input v-model:value="formState.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="内容" name="content" :rules="[{ required: true, message: '请输入内容' }]">
        <a-textarea v-model:value="formState.content" placeholder="请输入内容" />
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input-number v-model:value="formState.sort" placeholder="请输入排序" style="width: 250px" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import useModal from "@/utils/useModal";
import { reactive, ref } from "vue";
import { message } from "ant-design-vue";
import { add, edit } from "@/api/systemQa";
const { visible, modalTitle } = useModal();

const emits = defineEmits(["model-success"]);
const formRef = ref();

const formState = reactive({
  title: "",
  sort: 0,
  content: "",
});
const show = (model) => {
  visible.value = true;
  modalTitle.value = model ? "编辑问答" : "新增问答";
  if (model && model.qa_id) {
    resetForm(model);
  } else {
    resetForm({
      qa_id: null,
      sort: 0,
      content: "",
    });
  }
};
//设置表单的值
const resetForm = function (values) {
  for (var i in values) {
    formState[i] = values[i];
  }
};
// 保存
const handleOk = async () => {
  await formRef.value.validate().then(() => {
    let params = {
      ...formState,
    };
    if (formState.qa_id) {
      edit({
        id: formState.qa_id,
        ...params,
      }).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          formRef.value.resetFields();
          visible.value = false;
          emits("model-success");
        }
      });
    } else {
      //添加
      add({ ...params }).then(function (res) {
        if (res.code == 0) {
          message.success(res.msg);
          formRef.value.resetFields();
          visible.value = false;
          emits("model-success");
        }
      });
    }
  });
};
const handleCancel = () => {
  formRef.value.resetFields();
};
defineExpose({
  show,
});
</script>